# @Time    : 2022/2/1 12:23
# @Author  : junbaibai
# @File    : hoi_file_parser.py
import os.path
import pathlib
import re
import shutil

import py7zr

from src.db.obj.save_node import SaveNode
from src.utils.logger import Logger
from src.utils.timer import timer

logger = Logger(__name__)


class SaveAsBinaryNotEngException(Exception):
    def __str__(self):
        return "钢铁雄心四setting文件需要设置save_as_binary=no，否则无法解析"


class NotIronManException(Exception):
    def __str__(self):
        return "钢铁雄心四setting文件需要设置save_as_binary=no，否则无法解析"


class HoiParser:
    _pattern = re.compile(
        "\s*player=\"(.*)\"\s*ideology=(.*)\s*date=\"(.*)\"\s*difficulty=\"(.*)\"\s*version=\"(.*)\"\s*ironman=\"(.*)\"\s*")

    @staticmethod
    @timer
    def save(obj: SaveNode):
        src_path = obj.src_path
        dst_path = obj.file_path
        save_folder = pathlib.Path(dst_path).parent
        if not os.path.exists(save_folder.as_posix()):
            os.makedirs(save_folder.as_posix())
        tmp = f"{dst_path}.tmp"
        shutil.copy(src_path, tmp)
        zf = py7zr.SevenZipFile(dst_path, mode='w')
        zf.write(tmp, pathlib.Path(src_path).name)
        zf.close()
        os.remove(tmp)

    @staticmethod
    @timer
    def restore(obj: SaveNode):
        zf = py7zr.SevenZipFile(obj.file_path, mode="r")
        if os.path.exists(obj.src_path):
            os.remove(obj.src_path)
        zf.extract(path=pathlib.Path(obj.src_path).parent.as_posix(), targets=[pathlib.Path(obj.src_path).name])
        zf.close()

    @staticmethod
    def parse(file_path) -> SaveNode:
        try:
            with open(file_path, "r", encoding="utf-8") as fp:
                obj = SaveNode()
                obj.src_path = file_path
                content = fp.read()
                res = HoiParser._pattern.findall(content)

                if res.__len__() == 1:
                    for key, value in zip(obj.hoi_field, res[0]):
                        setattr(obj, key, value)

                obj.init_file_path()
                return obj
        except AttributeError as e:
            raise NotIronManException()

        except Exception as e:
            raise SaveAsBinaryNotEngException()


if __name__ == '__main__':
    hoi = HoiParser.parse("../  prc.hoi4")
    hoi.file_path = "../  prc.hoi4"
